package com.tc.service.impl;

import com.tc.OrderDto.Order;
import com.tc.OrderDto.OrderDetail;
import com.tc.OrderDto.OrderFood;
import com.tc.dto.Result;
import com.tc.factory.ResultFactory;
import com.tc.mapper.OrderMapper;
import com.tc.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ResultFactory result;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private ExecutorService executorService;
    @Autowired
    private OrderMapper orderMapper;
    //添加订单
    @Transactional
    @Override
    public Result addOrder(Order order, HttpServletRequest request){
        //获取用户id
        String id = request.getHeader("id");
        //存入redis和mysql,使用线程池完成异步操作
        executorService.submit(()->{
            //由于查询订单查询的是查redis,所以先存redis
            String uuid=UUID.randomUUID()
                            .toString();//用UUID作为value的key,value就是订单

            order.getInformation()
                 .setPayTime(LocalDateTime.now());//设置订单提交时间

            redisTemplate.opsForHash()
                         .put(id,uuid,order);
            //然后将数据进行解构,依次存入mysql,首先插入订单表
            orderMapper.addOrder(OrderDetail.builder()
                                            .id(null)
                                            .orderNumber(uuid)
                                            .userId(Integer.valueOf(id))
                                            .ipone(order.getInformation().getIphone())
                                            .address(order.getInformation().getPlace())
                                            .note(order.getInformation().getNote())
                                            .price(order.getInformation().getPrice())
                                            .createTime(LocalDateTime.now())
                                            .state(0)
                                            .shopName(order.getInformation().getShopName())
                                            .img(order.getInformation().getImg())
                                            .bgImg(order.getInformation().getBgImg())
                                            .build());
            //将购买的菜品插入菜品与订单的关系表,注意这里可能不止一个菜品,所以首先获取订单id
            Integer orderId=orderMapper.getOrderId(uuid);
            for (OrderFood orderFood : order.getShoppingCar()) {
                orderMapper.addRelation(orderId,
                                        Integer.valueOf(orderFood.getFood().getId()),
                                        Integer.valueOf(orderFood.getNum()),
                                        orderFood.getFood().getBelongCategory());
            }
        });
        return result.success("success");
    }

    //获取用户所有订单
    @Override
    public Result getAllOrder(HttpServletRequest request){
        //直接根据id查询redis,随后再解构数据
        String id=request.getHeader("id");
        Map<Object, Object> map=redisTemplate.opsForHash().entries(id);
        //倒序一下，否则是先进先出
        return result.success(map);
    }

    //删除订单
    @Transactional
    @Override
    public Result deleteOrder(Order item, String orderNumber, HttpServletRequest request) {
        //获取id
        String id=request.getHeader("id");
        //子线程删除mysql
        executorService.submit(()->{
            //首先获取订单的主键id
            Integer orderId=orderMapper.selectOrderId(orderNumber);
            //然后删除订单列表
            orderMapper.deleteOrder(id,orderNumber);
            //最后删除订单与菜品的关系表
            orderMapper.deleteOrderFoods(orderId);
        });
        //主线程删redis
        redisTemplate.opsForHash().delete(id,orderNumber);
        return result.success();
    }
}
